package ip.command;
/***********************************************************************
 * Module:  LoginCommand.java
 * Author:  mojsilo
 * Purpose: Defines the Class LoginCommand
 ***********************************************************************/

import ip.dto.UserDTO;
import ip.ejb.session.facade.UserFacadeLocal;
import ip.ejb.session.facade.UserFacadeLocalHome;
import ip.exceptions.NoSuchUserException;
import ip.exceptions.UnexpectedException;
import ip.util.EJBHomeFactory;

import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.RemoveException;
import javax.naming.NamingException;

import org.apache.log4j.Logger;

public class LoginCommand extends Command
{
	private UserDTO userDTO;
	private UserFacadeLocal userFacadeLocal;
	private Logger logger = Logger.getLogger(this.getClass());

	public void init() throws UnexpectedException{
		try {
			logger.debug("init()");
//			userFacadeLocal = (UserFacadeLocal) EJBHomeFactory.getInstance().create("ip/ejb/facade/UserFacadeLocal");								
			UserFacadeLocalHome userFacadeLocalHome = (UserFacadeLocalHome) EJBHomeFactory.getInstance().createLocalHome(ip.ejb.session.facade.UserFacadeLocalHome.class);
			userFacadeLocal = userFacadeLocalHome.create();
		} catch (NamingException e) {
			logger.error(e);
			e.printStackTrace();
			throw new UnexpectedException();			
		} catch (CreateException e) {
			logger.error(e);
			e.printStackTrace();
			throw new UnexpectedException();			
		}
	}

	public void execute() throws NoSuchUserException, UnexpectedException{
		try {
			logger.debug("execute()"); 

			if(userDTO.getRole().equals("a"))
				userDTO = userFacadeLocal.getAdmin(userDTO.getUsername(), userDTO.getPassword(),userDTO.getRole());				
			else
				userDTO = userFacadeLocal.getUser(userDTO.getUsername(), userDTO.getPassword());
			logger.debug("execute(): " + userDTO);
		} catch (NoSuchUserException e) {	
			logger.error(e);
			e.printStackTrace();
			throw new NoSuchUserException(userDTO.getUsername(), userDTO.getPassword());
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			throw new UnexpectedException();			
		}
	}

	public void dispose() throws UnexpectedException
	{
		try {
			userFacadeLocal.remove();
		} catch (EJBException e) {
			logger.error(e);
			e.printStackTrace();
			throw new UnexpectedException();			
		} catch (RemoveException e) {
			logger.error(e);
			e.printStackTrace();
			throw new UnexpectedException();			
		}
	}

	public UserDTO getUserDTO()
	{
		return userDTO;
	}

	public void setUserDTO(UserDTO userDTO) {
		this.userDTO = userDTO;
	}

}